import ResLoader, { resLoader, CompletedCallback, LoadResArgs, ProcessCallback } from "./ResLoader";

export interface autoResInfo {
    url: string;
    use: string;
    type?: typeof cc.Asset;
};

const {ccclass, property} = cc._decorator;
@ccclass
export default class ResKeeper extends cc.Component {
    private autoRes: autoResInfo[] = [];
    public loadRes(url: string);
    public loadRes(url: string, onCompleted: CompletedCallback);
    public loadRes(url: string, onProgess: ProcessCallback, onCompleted: CompletedCallback);
    public loadRes(url: string, type: typeof cc.Asset);
    public loadRes(url: string, type: typeof cc.Asset, onCompleted: CompletedCallback);
    public loadRes(url: string, type: typeof cc.Asset, onProgess: ProcessCallback, onCompleted: CompletedCallback);
    public loadRes() {
        let resArgs: LoadResArgs = ResLoader.makeLoadResArgs.apply(this, arguments);
        resArgs.use = resLoader.nextUseKey();
        let callback = resArgs.onCompleted;
        resArgs.onCompleted = (error: Error, res) => {
            if (!error) {
                this.autoRes.push({ url : resArgs.url, use : resArgs.use, type: resArgs.type});
            }
            callback && callback(error, res);
        }
        resLoader.loadRes(resArgs);
    }
    public onDestroy_Node() {
        console.log('onDestroy_Node')
        this.releaseAutoRes();
    }
    public releaseAutoRes() {
        for (let index = 0; index < this.autoRes.length; index++) {
            const element = this.autoRes[index];
            resLoader.releaseRes(element.url, element.type, element.use);
        }
        this.autoRes.length = 0;
    }
    public autoReleaseRes(resConf: autoResInfo, createUse: boolean = true) {
        if(!createUse || resLoader.addUse(resConf.url, resConf.use)) {
            this.autoRes.push(resConf);
        }
        console.log(this.autoRes);
    }
}
